package com.lyhengtongwl.zqsnews.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.OnClick;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.SlidingTabLayout;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.PagerAdapter;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.BaseEntity;
import com.lyhengtongwl.zqsnews.entity.BaseEventEntity;
import com.lyhengtongwl.zqsnews.entity.BidEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.fragment.goodsdetail.AppraiseFragment;
import com.lyhengtongwl.zqsnews.ui.fragment.goodsdetail.DetailFragment;
import com.lyhengtongwl.zqsnews.ui.fragment.goodsdetail.GoodsFragment;
import com.lyhengtongwl.zqsnews.ui.fragment.goodsdetail.PastSuccessFragment;
import com.lyhengtongwl.zqsnews.utils.*;
import com.lyhengtongwl.zqsnews.widget.BanSeekBar;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.lyhengtongwl.zqsnews.widget.NoScrollViewPager;
import org.greenrobot.eventbus.EventBus;
import retrofit2.Response;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Steven on 2019/1/15.
 * 商品详情页  逻辑   ：   目前是   根据goodId  先查询 详情内容   然后根据 salesType区分  竞拍 和 普通商品，
 */
public class GoodsDetailActivity extends BaseActivity {
    private List<Fragment> mFragments = new ArrayList<>();
    private final String[] mTitlesCommon = {"商品", "详情", "评价"};
    private final String[] mTitlesBids = {"商品", "详情", "评价", "往期成交"};
    private String goodId;//商品编号
    private String salesType;//拼团或者普通、竞拍
    private JSONObject jsonObject_share;
    private String issuedNo;//商品编号
    private BidEntity.ResultBean bidGoodsDetail = null;
    //标题栏容器
    @BindView(R.id.header_rel)
    RelativeLayout headerRel;

    //选项卡
    @BindView(R.id.stl)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.vp)
    NoScrollViewPager viewPager;
    @BindView(R.id.back_img)
    ImageView backImg;
    @BindView(R.id.share_img)
    ImageView shareImg;
    //左右两个按钮
    @BindView(R.id.back_img1)
    ImageView backImg1;
    @BindView(R.id.share_img1)
    ImageView shareImg1;

    private int titleHeight = 0;//标题栏高度
    //普通和虚拟商品
    @BindView(R.id.ll_good)//总得底部导航栏
            LinearLayout llGood;
    @BindView(R.id.ll_collection1)//收藏
            LinearLayout llCollection1;
    @BindView(R.id.tv_buyNow)//立即购买
            TextView tv_buyNow;
    //收藏按钮
    @BindView(R.id.img_collection1)
    ImageView imgCollection1;
    @BindView(R.id.tv_collection1)
    TextView tvCollection1;
    //竞拍商品
    @BindView(R.id.ll_bidOffer)//总得底部导航栏
            LinearLayout ll_bidOffer;
    //收藏按钮
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.tv_collection)
    TextView tvCollection;

    //竞拍商品 底部导航栏
    @BindView(R.id.bid_progress)  //进度条
            LinearLayout bid_progress;
    @BindView(R.id.progressBar)
    BanSeekBar progressBar;
    @BindView(R.id.tv_chujiazhong)//出价中
            TextView tv_chujiazhong;
    @BindView(R.id.rl_addOrMinus)//加减价
            RelativeLayout rl_addOrMinus;
    @BindView(R.id.tv_bidJiShu)//拍币
            TextView tv_bidJiShu;

    @BindView(R.id.tv_price)//展示基数
            EditText tv_price;
    private int jishu;
    private boolean isRefreshNow = true;//默认上去得开启刷新
    private boolean isStop = false;//默认是暂停刷新了
    private JSONObject jsonObject;//
    private JSONObject changeObject;
    private String myBiddingStatus = "";//全局的 竞拍状态 会更新
    private boolean isFirst = true;//默认上去第一次
    //处理刷新任务
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //处理刷新
                    if (isRefreshNow && "1".equals(salesType)) {  //只有竞拍商品才能刷新
                        refresh();
                    }
                    break;
            }
        }
    };

    //刷新
    private void refresh() {
        //0  表示未参与竞拍  1  表示竞拍中
        if ("20".equals(SPUtils.get(App.getContext(), "status", "00")) && ("0".equals(myBiddingStatus) || "1".equals(myBiddingStatus))) {
            Task.getApiService().refresh(issuedNo).enqueue(new MyCallback<BaseEntity>(this) {
                @Override
                protected void onSuccess(Response<BaseEntity> response) {
                    if ("0".equals(response.body().getCode())) {
                        changeObject = response.body().getResult();
                        //表示刷新成功
                        myBiddingStatus = response.body().getResult().getString("myBiddingStatus");//更改  竞拍状态的值
                        //弹窗问题
                        checkBiddingStatus(response.body().getResult());
                        //处理事务  开始更新ui 信息
                        JSONObject object = response.body().getResult();
                        BaseEventEntity baseEventEntity = new BaseEventEntity();
                        baseEventEntity.setTitle("detail");
                        baseEventEntity.setResult(object);
                        EventBus.getDefault().post(baseEventEntity);
                        mHandler.sendEmptyMessageDelayed(0, Long.parseLong(SPUtils.get(App.getContext(), "refreshDelayTime", "3000") + ""));
                    } else {
                        JSONObject object = response.body().getResult();
                        EventBus.getDefault().post(object);
                    }
                }

                @Override
                protected void onFailure(Throwable t) {

                }
            });
        } else {
            mHandler.sendEmptyMessageDelayed(0, Long.parseLong(SPUtils.get(App.getContext(), "refreshDelayTime", "3000") + ""));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isRefreshNow = false;
        isStop = true;
        mHandler.removeMessages(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRefreshNow = true;
        if (isStop) {
            mHandler.sendEmptyMessageDelayed(0, Long.parseLong(SPUtils.get(App.getContext(), "refreshDelayTime", "3000") + ""));
        }
    }

    @Override
    public void setListen() {

    }

    @SuppressLint("SetTextI18n")
    @OnClick({R.id.back_img, R.id.back_img1, R.id.share_img, R.id.share_img1, R.id.back_ll, R.id.ll_collection1, R.id.ll_collection, R.id.tv_buyNow, R.id.iv_add, R.id.iv_minus, R.id.tv_bidJiShu})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.back_ll:
            case R.id.back_img1:
            case R.id.back_img:
                finish();
                break;
            case R.id.share_img:
            case R.id.share_img1:
                ShowShareUtils.showShareDialog(this, getSupportFragmentManager(), jsonObject_share);
                break;
            case R.id.ll_collection1: //收藏图标
            case R.id.ll_collection://竞拍收藏
                collectionGood();
                break;
            case R.id.tv_buyNow://立即购买
                //判断 是否登录
                if (UserUtils.checkLogin()) {
                    startActivity(new Intent(GoodsDetailActivity.this, ConfirmOrderActivity.class)
                            .putExtra("my_type", "good")
                            .putExtra("Id", issuedNo)
                            .putExtra("salesType", salesType));
                } else {
                    startActivity(new Intent(GoodsDetailActivity.this, LoginAndRegisterActivity.class));
                }
                break;
            case R.id.iv_add://点击加号
                tv_price.setText(Integer.parseInt(tv_price.getText().toString()) + jishu + "");
                break;
            case R.id.iv_minus://点击减号
                if (Integer.parseInt(tv_price.getText().toString()) < jishu) {
                    ToastUtil.showShort(App.getContext(), "不能再减了，亲！");
                    return;
                }
                tv_price.setText(Integer.parseInt(tv_price.getText().toString()) - jishu + "");
                break;
            case R.id.tv_bidJiShu://竞拍出币
                String status = SPUtils.get(App.getContext(), "status", "00") + "";//0.待上架；10.预售中；20.出售（竞拍）中；30.已售罄；40.已下架；
                //myBiddingStatus：-1：竞拍结束；0，未参与竞拍（已消耗）；1，竞拍中；2，竞拍成功；
                if ("10".equals(status) || ("20".equals(status) && "0".equals(myBiddingStatus))) {
                    bid();
                } else {
                    ToastUtil.showShort(GoodsDetailActivity.this, "此时无法参与竞拍！");
                }

                break;
        }
    }

    //竞拍出币
    private void bid() {
        String str = tv_price.getText().toString();
        int count = Integer.parseInt(str);
        if (count < 0) {
            ToastUtil.showShort(App.getContext(), "竞拍基数得大于零！");
            return;
        }
        Task.getApiService().bid(issuedNo, str).enqueue(new MyCallback<BaseEntity>(GoodsDetailActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {

                String code = response.body().getCode();
                if ("0".equals(code)) { //表示拍中商品  开始出价
                    setBidProgress();
                } else if ("999".equals(code)) {//表示金额不足  需要充钱
                    String title = "余额不足";
                    String content = response.body().getResult().get("message") + "";//返回信息
                    String recharge_amount = response.body().getResult().get("") + ""; //需要支付的金额
                    showPrompt(title, content);
                } else if ("1".equals(response.body().getCode())) {//非法竞拍状态
                    String msg = response.body().getMessage();
                    ToastUtil.showShort(GoodsDetailActivity.this, msg);
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //展示 提示框  余额不足的情况下
    private void showPrompt(String title, String content) {
        new CenterDialog(R.layout.bid_promapt, GoodsDetailActivity.this).showPrompt(title, content);
    }

    //收藏商品
    private void collectionGood() {
        String token = SPUtils.get(App.getContext(), Constant.CommonInfo.TOKEN, "") + "";
        Task.getApiService().collectionGood(token, goodId).enqueue(new MyCallback<BaseEntity>(GoodsDetailActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    if (salesType.equals("1")) {
                        if ("收藏成功".equals(response.body().getResult().get("message"))) {
                            imgCollection.setImageResource(R.drawable.detail_collect01);
                            tvCollection.setText("取消收藏");
                        } else {
                            imgCollection.setImageResource(R.drawable.detail_collect);
                            tvCollection.setText("收藏");
                        }
                    } else {
                        if ("收藏成功".equals(response.body().getResult().get("message"))) {
                            imgCollection1.setImageResource(R.drawable.detail_collect01);
                            tvCollection1.setText("取消收藏");
                        } else {
                            imgCollection1.setImageResource(R.drawable.detail_collect);
                            tvCollection1.setText("收藏");
                        }
                    }
                    ToastUtil.showShort(App.getContext(), response.body().getResult().getString("message"));
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }


    @Override
    public void setTitleBarColor() {
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_detail;
    }

    @Override
    public void initView() {
        titleHeight = ScreenUtil.getStatusBarHeight(this) + ScreenUtil.dip2px(this, 50);
    }

    @Override
    public void initData() {
        issuedNo = getIntent().getStringExtra("issuedNo");//获取商品发行编号
        getGoodDetail();//获取详情初始化 商品详情信息
    }

    //加载商品详情数据
    private void getGoodDetail() {
        Task.getApiService().getGoodDetail(issuedNo).enqueue(new MyCallback<BaseEntity>(GoodsDetailActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        jsonObject_share = (JSONObject) JSON.toJSON(response.body().getResult().get("actionUrl"));
                        salesType = response.body().getResult().get("salesType") + "";
                        jsonObject = response.body().getResult();
                        changeObject = response.body().getResult();
                        if (("1").equals(salesType)) {
                            myBiddingStatus = jsonObject.getString("myBiddingStatus");//初始化值
                            checkBiddingStatus(jsonObject);
                        }
                        if (jsonObject.containsKey("isFavorite"))
                            setCollection(jsonObject.getBoolean("isFavorite"));
                        initFragment(jsonObject);
                        mHandler.sendEmptyMessageDelayed(0, Long.parseLong(SPUtils.get(App.getContext(), "refreshDelayTime", "3000") + ""));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //设置竞拍商品  进度条  BidEntity.ResultBean bidGoodsDetail
    private void setBidProgress() {
        String totality = changeObject.getString("myBiddingTotality");
        String biddingCount = changeObject.getString("myBiddingCount");
        int aa = 0;
        if (!"0".equals(totality)) {
            aa = getProgress(biddingCount, totality);
        }
        progressBar.setProgress(aa);
        bid_progress.setVisibility(View.VISIBLE);//进度条显示  表示已经参与竞拍
        rl_addOrMinus.setVisibility(View.GONE);//加减号  隐藏掉
        tv_chujiazhong.setVisibility(View.VISIBLE);
        tv_bidJiShu.setVisibility(View.GONE);
    }

    //获取 进度条进度
    private int getProgress(String count, String total) {
        try {
            BigDecimal bi1 = new BigDecimal(count);
            BigDecimal bi2 = new BigDecimal(total);
            BigDecimal divide = (bi1.divide(bi2, 2, RoundingMode.HALF_UP));
            return (int) (Double.parseDouble(divide.toString()) * 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //初始化  fragment信息 虚拟/普通   竞拍
    private void initFragment(JSONObject bean) {
        goodId = bean.getString("goodsId");
        if (salesType.equals("1")) {
            //表示竞拍商品
            ll_bidOffer.setVisibility(View.VISIBLE);
            llGood.setVisibility(View.GONE);
            mFragments.add(new GoodsFragment(bean, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            mFragments.add(new DetailFragment(goodId, titleHeight, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            mFragments.add(new AppraiseFragment(goodId, titleHeight, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            mFragments.add(new PastSuccessFragment(goodId, titleHeight, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), mFragments, mTitlesBids));
            viewPager.setOffscreenPageLimit(3);
            slidingTabLayout.setViewPager(viewPager);
        } else {
            //表示普通和虚拟商品
            llGood.setVisibility(View.VISIBLE);
            ll_bidOffer.setVisibility(View.GONE);
            mFragments.add(new GoodsFragment(bean, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            mFragments.add(new DetailFragment(goodId, titleHeight, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            mFragments.add(new AppraiseFragment(goodId, titleHeight, headerRel, slidingTabLayout, backImg, shareImg, backImg1, shareImg1));
            viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), mFragments, mTitlesCommon));
            viewPager.setOffscreenPageLimit(3);
            slidingTabLayout.setViewPager(viewPager);
        }
    }

    //设置 收藏 按钮显示问题
    private void setCollection(boolean isIsFavorite) {
        if (salesType.equals("1")) {
            if (isIsFavorite) {
                imgCollection.setImageResource(R.drawable.detail_collect01);
                tvCollection.setText("取消收藏");
            } else {
                imgCollection.setImageResource(R.drawable.detail_collect);
                tvCollection.setText("收藏");
            }
        } else {
            if (isIsFavorite) {
                imgCollection1.setImageResource(R.drawable.detail_collect01);
                tvCollection1.setText("取消收藏");
            } else {
                imgCollection1.setImageResource(R.drawable.detail_collect);
                tvCollection1.setText("收藏");
            }
        }
    }

    //根据myBiddingStatus 判断竞拍状态
    private void checkBiddingStatus(JSONObject object) {
        String biddingMsg = "";
        if (object.containsKey("myBiddingMessage")) {
            biddingMsg = object.getString("myBiddingMessage");
        }
        switch (myBiddingStatus) {
            case "-1"://竞拍结束  表示  竞拍结束  其他人竞拍成功  表示别人中奖
                setBidButton();
                isRefreshNow = false;
                new CenterDialog(R.layout.bid_fail_layout, GoodsDetailActivity.this).showPrompt_fail("幸运儿已产生", biddingMsg, jsonObject.getString("issuedNo"));
                break;
            case "0"://未参与竞拍(已消耗) 此时可以参与竞拍
                setBidButton();
                break;
            case "1"://竞拍中  控制进度条显示
                setBidProgress();
                break;
            case "2"://竞拍成功  弹出 自己竞拍成功的弹窗
                setBidButton();
                isRefreshNow = false;
                new CenterDialog(R.layout.bid_success_layout, GoodsDetailActivity.this).showPrompt_success("恭喜你拍中", biddingMsg, object.getString("myBiddingOrderId"), salesType);
                break;
        }
    }

    //设置 显示 竞拍次数  和 竞拍按钮
    @SuppressLint("SetTextI18n")
    private void setBidButton() {
        if (isFirst) {
            isFirst = false;
            jishu = Integer.parseInt(jsonObject.getString("biddingGrowthCount"));
            tv_price.setText(jsonObject.getString("biddingBaseCount"));
            tv_bidJiShu.setText(jsonObject.getString("biddingUnit") + "拍币/次"); //只设置一次
        }
        bid_progress.setVisibility(View.GONE);//进度条显示  表示已经参与竞拍
        rl_addOrMinus.setVisibility(View.VISIBLE);//加减号  隐藏掉
        tv_chujiazhong.setVisibility(View.GONE);
        tv_bidJiShu.setVisibility(View.VISIBLE);
    }
}
